package com.llan;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import org.junit.Test;

import static org.junit.Assert.*;

/**
 * Created by llan on 2018/5/23 21:17.
 */
public class HystrixStubbedFallback extends HystrixCommand<HystrixStubbedFallback.UserAccount> {

    private final int customerId;
    private final String countryCodeFromGeoLookup;

    /**
     * @param customerId 用于检索UserAccount
     * @param countryCodeFromGeoLookup
     *            来自HTTP请求geo代码查找的默认国家代码用于回退。
     */
    protected HystrixStubbedFallback(int customerId, String countryCodeFromGeoLookup) {
        super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
        this.customerId = customerId;
        this.countryCodeFromGeoLookup = countryCodeFromGeoLookup;
    }

    @Override
    protected UserAccount run() {
        // 从远程服务获取UserAccount
        //    返回  UserAccountClient.getAccount(customerId);
        throw new RuntimeException("forcing failure for example"); //模拟异常用于触发回滚
    }

    @Override
    protected UserAccount getFallback() {
        /**
         * 返回有一些静态默认值，占位符，还有一个注入的我们将使用的值'countryCodeFromGeoLookup'。
         * 而不是我们从远程服务检索出来的
         */
        return new UserAccount(customerId, "Unknown Name",
                countryCodeFromGeoLookup, true, true, false);
    }


    public static class UnitTest {

        @Test
        public void test() {
            HystrixStubbedFallback command = new HystrixStubbedFallback(1234, "ca");
            UserAccount account = command.execute();
            assertTrue(command.isFailedExecution());
            assertTrue(command.isResponseFromFallback());
            assertEquals(1234, account.customerId);
            assertEquals("ca", account.countryCode);
            assertEquals(true, account.isFeatureXPermitted);
            assertEquals(true, account.isFeatureYPermitted);
            assertEquals(false, account.isFeatureZPermitted);
        }
    }

    public static class UserAccount {
        private final int customerId;
        private final String name;
        private final String countryCode;
        private final boolean isFeatureXPermitted;
        private final boolean isFeatureYPermitted;
        private final boolean isFeatureZPermitted;

        UserAccount(int customerId, String name, String countryCode,
                    boolean isFeatureXPermitted,
                    boolean isFeatureYPermitted,
                    boolean isFeatureZPermitted) {
            this.customerId = customerId;
            this.name = name;
            this.countryCode = countryCode;
            this.isFeatureXPermitted = isFeatureXPermitted;
            this.isFeatureYPermitted = isFeatureYPermitted;
            this.isFeatureZPermitted = isFeatureZPermitted;
        }
    }
}
